import 'package:flutter/material.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:provider/provider.dart';
import 'package:untitled/pages/login_page.dart';
import 'package:untitled/pages/main_page.dart';
import 'package:untitled/viewmodel/home/add_friend/add_friend_view_model.dart';
import 'package:untitled/viewmodel/home/chat/chat_view_model.dart';
import 'package:untitled/viewmodel/home/friend_info/friend_info_view_model.dart';
import 'package:untitled/viewmodel/home/home_view_model.dart';
import 'package:untitled/viewmodel/login_view_model.dart';

import 'config.dart';
import 'core/store/user_store.dart';
import 'core/utils/global_context.dart';

// 1. 声明全局 RouteObserver 实例
final RouteObserver<ModalRoute<void>> routeObserver = RouteObserver<ModalRoute<void>>();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Store().init();

  runApp(
    OverlaySupport.global(
      child: MultiProvider(
        providers: [
          ChangeNotifierProvider(create: (_) => LoginViewModel()..loadLogin()),
          ChangeNotifierProvider(create: (_) => AddFriendViewModel()),
          ChangeNotifierProvider(create: (_) => FriendInfoViewModel()),
          ChangeNotifierProvider(create: (_) => HomeViewModel()),
          ChangeNotifierProvider(create: (_) => ChatViewModel()),
        ],
        child: MaterialApp(
          navigatorKey: navigatorKey,
          debugShowCheckedModeBanner: Config.enableDebug,
          home: const MyApp(),

          // 2. 把 routeObserver 传给 MaterialApp 的 navigatorObservers
          navigatorObservers: [routeObserver],
        ),
      ),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    final loginVM = Provider.of<LoginViewModel>(context);
    return loginVM.isLoggedIn ? const MainPage() : const LoginPage();
  }
}